package com.bx.implatform.growUp.service.Impl;

import com.bx.implatform.growUp.entity.Bridge;
import com.bx.implatform.growUp.mapper.ConserveMapper;
import com.bx.implatform.growUp.service.ConserveService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class ConserveServiceImpl implements ConserveService {

    private final ConserveMapper conserveMapper;

    /**
     * 桥梁概况
     *
     * @return
     */
    @Override
    public Map<String, Map<String, Object>> bridge() {
        Map<String, Map<String, Object>> resultMap = new HashMap<>();
        List<Bridge> bridgeList = conserveMapper.bridge();

        if (!bridgeList.isEmpty()) {
            // 统计总数据
            Map<String, Object> map1 = new HashMap<>();
            map1.put("总里程", bridgeList.stream().mapToDouble(Bridge::getTotalLength).sum());
            map1.put("总座数", bridgeList.size());
            resultMap.put("top-统计", map1);

            // 分类统计
            Map<String, List<Bridge>> bridgesByCategory = bridgeList.stream()
                    .collect(Collectors.groupingBy(
                            bridge -> bridge.getBridgeCategory() != null ? bridge.getBridgeCategory() : "未分类"
                    ));

            Map<String, Object> map2 = new HashMap<>();
            Map<String, Object> map3 = new HashMap<>();

            double totalLength = bridgeList.stream().mapToDouble(Bridge::getTotalLength).sum();

            bridgesByCategory.forEach((key, value) -> {
                // 计算座数百分比（保留2位小数）
                double countPercentage = (double) value.size() / bridgeList.size() * 100;
                map2.put(key, Math.round(countPercentage * 100.0) / 100.0);

                // 计算里程百分比（保留2位小数）
                double lengthPercentage = value.stream().mapToDouble(Bridge::getTotalLength).sum() / totalLength * 100;
                map3.put(key, Math.round(lengthPercentage * 100.0) / 100.0);
            });

            resultMap.put("end-座数比", map2);
            resultMap.put("end-里程比", map3);

            return resultMap;
        }
        return null;
    }
}
